﻿using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing.Imaging;
using System.Diagnostics;
using Aspects.Custom;
using Aspects.Unit;
using Aspects.Custom.Audio;
using System.Windows.Forms;
using System.Drawing;

namespace Aspects
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SetupDebugWindow();
            TerminateKeymon();
        }

        //Used to update all the labels in this form
        private void timer1_Tick(object sender, EventArgs e)
        {
            //TODO Update Battery
            //TODO update IP
        }

        #region Opening and Closing Operations

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            #if DEBUG
            StopTimers();
            StartKeyMon();
            #else
            if (!unitInformationPanel1.IsServiceTypeSelected())
            {
                e.Cancel = true;
                MessageBox.Show("Please select Production or Service", "Fial");
            }
            else
            {
                StopTimers();
                //audioBrightnessPanel1.StopSound();
                SavePanels();
                StartKeyMon();
            }
            #endif
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            unitInformationPanel1.PopulateUnitInformation();
            batteryInformationPanel1.InitializeBatteries();
            magStripeReaderPanel1.SetupPointOfSale();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            audioBrightnessPanel1.UpdateBrightnessTrackbar();
            applicationLauncherPanel1.LoadApplications();
            timer1.Start();
        }
        
        private void StopTimers()
        {
            timer1.Stop();
        }

        private void SavePanels()
        {
            Bitmap bm = new Bitmap(800, 600);
            int xOffSet = this.DisplayRectangle.X;
            int yOffSet = this.DisplayRectangle.Y;
            foreach (Control panel in this.Controls)
            {
                int x = panel.Location.X - xOffSet;
                int y = panel.Location.Y - yOffSet;
                int width = panel.Size.Width;
                int height = panel.Size.Height;
                panel.DrawToBitmap(bm, new Rectangle(x, y, width, height));
            }
            DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
            directory = directory.CreateSubdirectory("Pictures"); //if it already exists this method does nothing

            string serial = UnitSerialNumber.GetSerialNumber();
            string date = DateTime.Now.ToString("MMddyy");
            string type = unitInformationPanel1.GetServiceString();
            string pictureFile = directory.FullName + "\\";
            pictureFile += serial + "-" + date + "-" + type;

            try
            {
                bm.Save(pictureFile, ImageFormat.Png);
            }
            catch
            {
                MessageBox.Show("Saving picture failed", "Fial");
            }
        }

        private void StartKeyMon()
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                string[] dliDirectory = Directory.GetDirectories(@"C:\Program Files\DLI");
                string keyMonDirectory = string.Empty;
                foreach (string partDirectory in dliDirectory)
                {
                    if (partDirectory.EndsWith("KeyMon"))
                    {
                        keyMonDirectory = partDirectory;
                        break;
                    }
                }
                string[] files = Directory.GetFiles(keyMonDirectory);
                string keyMonFile = string.Empty;
                foreach (string partFiles in files)
                {
                    if (partFiles.EndsWith("KeyMon.exe"))
                    {
                        keyMonFile = partFiles;
                        break;
                    }
                }
                startInfo.WorkingDirectory = keyMonDirectory;
                startInfo.FileName = keyMonFile;
                Process.Start(startInfo);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        private void TerminateKeymon()
        {
            try
            {
                Process[] processes = Process.GetProcesses();
                foreach (Process proc in processes)
                {
                    if (proc.ProcessName.EndsWith("KeyMon"))
                    {
                        proc.Kill();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        #endregion

        #region Debug Data Information

        //[Conditional("DEBUG")]
        private void SetupDebugWindow()
        {
            Console.SetOut(new DebugWriter(DebugDataTextbox));
        }

        #endregion

        #region Point of Sale Information

        #endregion

        #region Com Port Data Information

        private void comPortOpenButton_Click(object sender, EventArgs e)
        {
            comPortCloseButton.Enabled = true;
            comPortOpenButton.Enabled = false;
        }

        private void comPortCloseButton_Click(object sender, EventArgs e)
        {
            comPortOpenButton.Enabled = true;
            comPortCloseButton.Enabled = false;
        }

        #endregion

        #region Keyboard Test Information

        private void KeyboardTestTextbox_KeyDown(object sender, KeyEventArgs e)
        {
            KeyboardTestTextbox.Clear();
            KeyboardTestTextbox.Text = " - " + e.KeyData.ToString();            
        }

        #endregion

        #region Camera Information

        #endregion

    }
}
